<template>
  <div class="login-title">
    <img class="icon" src="@/assets/image/logo.jpg" alt="logo" />
    <h2 class="title">成理工程学科竞赛管理系统</h2>
  </div>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
    <el-form-item v-if="!loginPhone" label="" prop="employeeNumber">
      <el-input
        v-model="ruleForm.employeeNumber"
        placeholder="请输入用户名"
        maxlength="50"
        auto-complete="on"
        style="position: relative"
        @keyup.enter="submitForm(ruleFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><UserFilled /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item v-if="!loginPhone" label="" prop="password">
      <el-input
        v-model="ruleForm.password"
        placeholder="请输入密码"
        auto-complete="on"
        :type="passwordType"
        @keyup.enter="submitForm(ruleFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><GoodsFilled /></el-icon>
        </template>
        <template #suffix>
          <div class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </div>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item v-if="loginPhone" prop="phone">
      <el-input
        v-model="ruleForm.phone"
        placeholder="请输入11位手机号"
        maxlength="11"
        auto-complete="on"
        style="position: relative"
        @keyup.enter="submitForm(ruleFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Iphone /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item v-if="loginPhone" prop="code">
      <el-input
        v-model="ruleForm.code"
        placeholder="请输入验证码"
        maxlength="6"
        auto-complete="on"
        style="position: relative"
        @keyup.enter="submitForm(ruleFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Position /></el-icon>
        </template>
        <template #suffix>
          <el-button :disabled="flag" class="code-btn" @click="getCode"> {{ flag ? `${countdown}s 后重新发送` : '获取验证码' }}</el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-tag style="cursor: pointer" type="info" @click="updateLogin">{{ loginPhone ? '账号登录' : '手机号登录' }}</el-tag>
    <el-form-item style="width: 100%">
      <el-button :loading="loading" class="login-btn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
    </el-form-item>
  </el-form>
  <Vcode :slider-size="35" :canvas-width="400" :canvas-height="220" :show="isShow" @success="onSuccess" @close="onClose" />
</template>
<script lang="ts" setup>
  import { ref, reactive, onUnmounted } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElNotification } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/store/modules/user'
  import { getTimeStateStr } from '@/utils/index'
  import { userLoginForm } from '@/types/user'
  import Vcode from 'vue3-puzzle-vcode' // 验证码组件
  import { getPhoneCodeService } from '@/api/user'
  const isShow = ref(false)
  const router = useRouter()
  const UserStore = useUserStore()
  const ruleFormRef = ref<FormInstance>()
  const passwordType = ref('password')
  const loading = ref(false)
  const loginPhone = ref(false) // 手机号码登录
  const flag = ref(false) // 获取验证码按钮禁用状态
  const countdown = ref(60) // 剩余秒数
  let timer = null // 定时器句柄
  const rules = reactive({
    employeeNumber: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      {
        pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
        message: '手机号格式不正确!',
        trigger: 'blur',
      },
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  })
  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })
  // 表单数据
  const ruleForm = reactive<userLoginForm>({
    employeeNumber: 'root', // 默认工号
    password: 'zw20030606.', // 默认密码
    phone: '',
    code: '',
  })
  /**获取验证码 */
  const getCode = async () => {
    await ruleFormRef.value.validateField('phone')
    // if (verifyPhone(ruleForm.phone) && !flag.value) {
    getPhoneCodeService({ phone: ruleForm.phone })
      .then(() => {
        ElMessage.success('验证码已发送，请注意查收')
      })
      .catch((err) => {
        ElMessage.error(err.message || '获取验证码失败，请稍后再试')
      })
    flag.value = true
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        flag.value = false
      }
    }, 1000)
    // }
  }
  // 显示密码图标
  const showPwd = () => {
    passwordType.value = passwordType.value === 'password' ? '' : 'password'
  }

  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        isShow.value = true
      }
    })
  }

  const onClose = () => {
    isShow.value = false
  }

  const onSuccess = async () => {
    isShow.value = false
    loading.value = true
    UserStore.login(ruleForm)
      .then(async () => {
        await router.push({
          path: '/',
        })
        ElNotification({
          title: getTimeStateStr(),
          message: '欢迎登录学科竞赛管理系统',
          type: 'success',
          duration: 2500,
        })
      })
      .catch((err) => {})
      .finally(() => {
        loading.value = false
      })
  }
  // 切换登录方式
  const updateLogin = () => {
    loginPhone.value = !loginPhone.value
    ruleFormRef.value?.resetFields()
  }
</script>

<style lang="scss" scoped>
  @import '../index.scss';
</style>
